import './ContextModal.css';
import {isNotEmpty} from '@/utils/CommonUtils';
import icons from '@/icons';
import createVueApp from '@/utils/createVueApp';

export default {
  name: 'ContextModal',
  props: {
    zIndex: {
      type: Number,
      default: 0
    },
    width: {
      type: Number,
      default: 270
    }
  },
  data() {
    return {
      items: [],
      x: 0,
      y: 0,
      visible: false
    };
  },
  methods: {
    setData(items, x, y) {
      this.items = items;
      this.x = x;
      this.y = y;
      this.open();
      if (this.x + this.width >= window.innerWidth) {
        this.x = window.innerWidth - this.width;
      }
    },
    open() {
      this.visible = true;

      this.$nextTick(() => {
        let height = $(this.$refs.fContextWrapper).height() + 20;
        if (height + this.y >= window.innerHeight) {
          this.y = window.innerHeight - height;
        }
      });
    },
    close() {
      this.visible = false;
      this.$emit('close');
    },
    getContainerStyle() {
      let res = {left: this.x + 'px', top: this.y + 'px'};
      if (this.zIndex) {
        res.zIndex = this.zIndex;
      }
      if (this.width) {
        res.width = `${this.width}px`;
      }
      return res;
    },
    getContainer() {
      return <div className="mask-container"
                  ref="fContextWrapper"
                  style={this.containerStyle}>
        {this.getItems()}
      </div>;
    },
    contextItemClick(e, item) {
      this.$emit('contextItemClick', item);
    },
    getItems() {
      let list = [];
      for (let i = 0; i < this.items.length; i++) {
        list.push(<div className="item"
                       onClick={(e) => this.contextItemClick(e, this.items[i])}>
          {this.getIcon(this.items[i])}
          <span style={{paddingLeft: '8px'}}>
            {this.items[i].title}
          </span>
        </div>);
      }
      return list;
    },
    getIcon(item) {
      if (isNotEmpty(item.icon)) {
        if (isNotEmpty(this.$slots[item.icon])) {
          return <span className="icon el-icon">
            {this.$slots[item.icon]()}
          </span>;
        }
        let iconComponent = icons.iconRegister[item.icon];
        if (isNotEmpty(iconComponent)) {
          return <iconComponent/>;
        }
      }
    },
  },
  render() {
    if (this.visible) {
      return <div>
        <div className="mask" style={{zIndex: this.zIndex}} onClick={this.close}/>
        {this.getContainer()}
      </div>;
    }
    return <div></div>;
  },
  computed: {
    containerStyle() {
      let res = {left: this.x + 'px', top: this.y + 'px'};
      if (this.zIndex) {
        res.zIndex = this.zIndex;
      }
      if (this.width) {
        res.width = `${this.width}px`;
      }
      return res;
    },
  }
};
